import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Boss {
    // 添加血量条相关属性
    private static final int HEALTH_BAR_WIDTH = 200;
    private static final int HEALTH_BAR_HEIGHT = 20;
    private static final int HEALTH_BAR_OFFSET_Y = 30;
    private Image heartImage;
    private static final int WIDTH = 150;
    private static final int HEIGHT = 150;
    private static final int MOVE_SPEED = 3;
    private static final int HIT_POINTS = 15;

    private int x;
    private int y;
    private int hits = 0;
    private boolean active = false;
    private Image bossImage;
    private int moveDirection = 1; // 1 for down, -1 for up
    private long lastMoveTime = 0;
    private static final long MOVE_INTERVAL = 1000; // 1 second

    // 攻击相关属性
    private static final long ATTACK_COOLDOWN = 1500; // 攻击冷却时间
    private long lastAttackTime = 0;
    private List<BeamAttack> beamAttacks = new ArrayList<>();
    private List<CircleAttack> circleAttacks = new ArrayList<>();
    private Image beamImage;
    private Image circleImage;
    private Random random = new Random();
    private int playerHits = 0; // 玩家被击中次数

    public Boss() {
        try {
            bossImage = new Image(getClass().getResourceAsStream("/images/boss.png"));
            beamImage = new Image(getClass().getResourceAsStream("/images/bossAttack1.png"));
            circleImage = new Image(getClass().getResourceAsStream("/images/bossAttack2.png"));
            heartImage = new Image(getClass().getResourceAsStream("/images/heart.png"));
        } catch (Exception e) {
            System.err.println("加载BOSS图像失败: " + e.getMessage());
        }
    }

    public void activate(int screenWidth, int screenHeight) {
        // 修改BOSS初始位置到屏幕70%:30%的位置
        x = (int)(screenWidth * 0.7) - WIDTH;
        y = (screenHeight - HEIGHT) / 2;
        hits = 0;
        active = true;
        playerHits = 0;
        beamAttacks.clear();
        circleAttacks.clear();
    }

    public void update() {
        if (!active) return;

        long currentTime = System.currentTimeMillis();

        // 随机移动（范围限制在屏幕中间区域）
        if (currentTime - lastMoveTime > MOVE_INTERVAL) {
            if (Math.random() < 0.3) {
                moveDirection *= -1;
            }
            lastMoveTime = currentTime;
        }

        y += MOVE_SPEED * moveDirection;

        // 边界检查（限制在屏幕中间60%区域）
        int minY = (int)(GameConstants.getScreenHeight() * 0.2);
        int maxY = (int)(GameConstants.getScreenHeight() * 0.8 - HEIGHT);

        if (y < minY) {
            y = minY;
            moveDirection = 1;
        } else if (y > maxY) {
            y = maxY;
            moveDirection = -1;
        }

        // 攻击逻辑
        if (currentTime - lastAttackTime > ATTACK_COOLDOWN) {
            if (random.nextDouble() < 0.6) {
                // 光束攻击 - 现在从BOSS中间发射
                beamAttacks.add(new BeamAttack(x, y + HEIGHT/2 - 40));
            } else {
                // 圆形弹幕 - 从BOSS中心发射
                circleAttacks.add(new CircleAttack(x + WIDTH/2, y + HEIGHT/2));
            }
            lastAttackTime = currentTime;
        }

        // 更新光束攻击
        for (int i = 0; i < beamAttacks.size(); i++) {
            BeamAttack attack = beamAttacks.get(i);
            attack.update();
            if (attack.isOutOfScreen()) {
                beamAttacks.remove(i);
                i--;
            }
        }

        // 更新圆形弹幕
        for (int i = 0; i < circleAttacks.size(); i++) {
            CircleAttack attack = circleAttacks.get(i);
            attack.update();
            if (attack.isFinished()) {
                circleAttacks.remove(i);
                i--;
            }
        }


        // 更新圆形弹幕
        for (int i = 0; i < circleAttacks.size(); i++) {
            CircleAttack attack = circleAttacks.get(i);
            attack.update();
            if (attack.isFinished()) {
                circleAttacks.remove(i);
                i--;
            }
        }
    }

    public void render(GraphicsContext gc) {
        if (active) {
            // 绘制BOSS
            gc.drawImage(bossImage, x, y, WIDTH, HEIGHT);

            // 绘制血条背景
            int barX = x + WIDTH/2 - HEALTH_BAR_WIDTH/2;
            int barY = y - HEALTH_BAR_OFFSET_Y;
            gc.setFill(javafx.scene.paint.Color.RED);
            gc.fillRect(barX, barY, HEALTH_BAR_WIDTH, HEALTH_BAR_HEIGHT);

            // 绘制当前血量
            double healthPercentage = (double)(HIT_POINTS - hits) / HIT_POINTS;
            gc.setFill(javafx.scene.paint.Color.GREEN);
            gc.fillRect(barX, barY, HEALTH_BAR_WIDTH * healthPercentage, HEALTH_BAR_HEIGHT);

            // 绘制血量数字
            gc.setFill(javafx.scene.paint.Color.WHITE);
            gc.setFont(javafx.scene.text.Font.font(16));
            String healthText = (HIT_POINTS - hits) + "/" + HIT_POINTS;
            gc.fillText(healthText, barX + HEALTH_BAR_WIDTH/2 - 20, barY + HEALTH_BAR_HEIGHT/2 + 5);

            // 渲染攻击
            for (BeamAttack attack : beamAttacks) {
                attack.render(gc);
            }

            for (CircleAttack attack : circleAttacks) {
                attack.render(gc);
            }
        }
    }

    public boolean checkHit(Bomb bomb) {
        if (!active || !bomb.active || bomb.exploding) return false;

        if (bomb.x + bomb.width > x &&
                bomb.x < x + WIDTH &&
                bomb.y + bomb.height > y &&
                bomb.y < y + HEIGHT) {

            hits++;
            bomb.explode();

            if (hits >= HIT_POINTS) {
                active = false;
            }
            return true;
        }
        return false;
    }

    // 检查玩家是否被攻击击中
    public boolean checkPlayerHit(Player player) {
        if (!active || playerHits >= 2) return false;

        boolean hit = false;

        // 检查光束攻击
        for (BeamAttack attack : beamAttacks) {
            if (attack.checkCollision(player.getX(), player.getY(),
                    player.getWidth(), player.getHeight())) {
                hit = true;
                player.setHitByBoss();
                break;
            }
        }

        // 检查圆形弹幕
        if (!hit) {
            for (CircleAttack attack : circleAttacks) {
                if (attack.checkCollision(player.getX(), player.getY(),
                        player.getWidth(), player.getHeight())) {
                    hit = true;
                    player.setHitByBoss();
                    break;
                }
            }
        }

        if (hit) {
            // 只有在玩家没有护盾或护盾未被击中时才增加击中次数
            if (!player.hasShield() || player.isShieldHit()) {
                playerHits++;
                System.out.println("玩家被击中，当前击中次数: " + playerHits);
            }
            return true;
        }

        return false;
    }

    // 检查2次击中
    public boolean isPlayerDefeated() {
        return playerHits >= 2;
    }

    public boolean isActive() {
        return active;
    }

    public void deactivate() {
        active = false;
    }


    // 光束攻击内部类 - 增大尺寸
    private class BeamAttack {
        private int x;
        private int y;
        private static final int WIDTH = 80; // 从50增大到80
        private static final int HEIGHT = 20; // 从10增大到20
        private static final int SPEED = 10;
        private boolean hasHitPlayer = false;

        public BeamAttack(int startX, int startY) {
            this.x = startX - WIDTH;
            this.y = startY;
        }

        public void update() {
            x -= SPEED;
        }

        public void render(GraphicsContext gc) {
            gc.drawImage(beamImage, x, y, WIDTH, HEIGHT);
        }

        public boolean isOutOfScreen() {
            return x + WIDTH < 0;
        }

        public boolean checkCollision(int playerX, int playerY, int playerWidth, int playerHeight) {
            if (hasHitPlayer) return false;

            boolean collided = playerX + playerWidth > x &&
                    playerX < x + WIDTH &&
                    playerY + playerHeight > y &&
                    playerY < y + HEIGHT;

            if (collided) {
                hasHitPlayer = true;
            }
            return collided;
        }
    }

    // 圆形弹幕内部类
    private class CircleAttack {
        private int centerX;
        private int centerY;
        private List<Projectile> projectiles = new ArrayList<>();
        private static final int PROJECTILE_COUNT = 24; // 从16增加到24个，更密集
        private static final int PROJECTILE_SIZE = 25; // 从15增大到25
        private static final int PROJECTILE_SPEED = 3; // 从4降到3，更慢
        private boolean spawned = false;

        private boolean hasHitPlayer = false; // 新增标志

        public CircleAttack(int centerX, int centerY) {
            this.centerX = centerX;
            this.centerY = centerY;
        }

        public void update() {
            if (!spawned) {
                // 生成24个方向的弹幕，角度间隔15度
                for (int i = 0; i < PROJECTILE_COUNT; i++) {
                    double angle = Math.toRadians(i * (360.0 / PROJECTILE_COUNT));
                    projectiles.add(new Projectile(
                            centerX, centerY,
                            Math.cos(angle) * PROJECTILE_SPEED,
                            Math.sin(angle) * PROJECTILE_SPEED
                    ));
                }
                spawned = true;
            }

            // 更新所有弹幕位置
            for (Projectile p : projectiles) {
                p.update();
            }
        }

        public void render(GraphicsContext gc) {
            for (Projectile p : projectiles) {
                gc.drawImage(circleImage, p.x, p.y, PROJECTILE_SIZE, PROJECTILE_SIZE);
            }
        }

        public boolean isFinished() {
            // 当所有弹幕都离开屏幕时攻击结束
            for (Projectile p : projectiles) {
                if (p.x > -50 && p.x < GameConstants.getScreenWidth() + 50 &&
                        p.y > -50 && p.y < GameConstants.getScreenHeight() + 50) {
                    return false;
                }
            }
            return true;
        }

        public boolean checkCollision(int playerX, int playerY, int playerWidth, int playerHeight) {
            if (hasHitPlayer) return false; // 如果已经击中过玩家，不再检测

            for (Projectile p : projectiles) {
                if (playerX + playerWidth > p.x &&
                        playerX < p.x + PROJECTILE_SIZE &&
                        playerY + playerHeight > p.y &&
                        playerY < p.y + PROJECTILE_SIZE) {
                    hasHitPlayer = true; // 标记为已击中
                    return true;
                }
            }
            return false;
        }


        private class Projectile {
            public double x;
            public double y;
            private double dx;
            private double dy;

            public Projectile(double x, double y, double dx, double dy) {
                this.x = x - PROJECTILE_SIZE/2;
                this.y = y - PROJECTILE_SIZE/2;
                this.dx = dx;
                this.dy = dy;
            }

            public void update() {
                x += dx;
                y += dy;
            }
        }
    }
}